/**
 * 等比缩放-根据宽度
 * @element {HTMLElement} 元素
 * @containerWidth {number} 容器宽度
 */
function setScaleByWidth(element, containerWidth) {
  const size = document.documentElement.clientWidth / containerWidth
  const size2 = `${100 / size}%`
  element.setAttribute('style', `transform:scale(${size});transform-origin:0 0;width:${size2};height:${size2};`)
}
/**
 * 等比缩放-根据高度
 * @element {HTMLElement} 元素
 * @containerHeight {number} 容器宽度
 */
function setScaleByHeight(element, containerHeight) {
  const size = document.documentElement.clientHeight / containerHeight
  const size2 = `${100 / size}%`
  element.setAttribute('style', `transform:scale(${size});transform-origin:0 0;width:${size2};height:${size2};`)
}
/**
 * 高级防抖
 * @func {Function} func 要执行的函数
 * @delay {number} delay 延时
 * @immediate {boolean} immediate 是否立即执行一次
 * @returns
 */
function debounce(func, delay, immediate) {
  let timer
  return function (...args) {
    timer && clearTimeout(timer)
    if (immediate) {
      const firstRun = !timer
      timer = setTimeout(() => {
        timer = null
      }, delay)
      if (firstRun)
        func.apply(this, args)
    }
    else {
      timer = setTimeout(() => {
        func.apply(this, args)
      }, delay)
    }
  }
}

/**
 * 禁止手动缩放
 */
function disableManualScale() {
  // 禁止Ctrl+滑轮缩放
  window.addEventListener('mousewheel', (event) => {
    if (event.ctrlKey === true || event.metaKey)
      event.preventDefault()
  }, { passive: false })

  // firefox浏览器
  window.addEventListener('DOMMouseScroll', (event) => {
    if (event.ctrlKey === true || event.metaKey)
      event.preventDefault()
  }, { passive: false })

  // 禁止Ctrl+ +/- 缩放
  document.addEventListener('keydown', (event) => {
    if ((event.ctrlKey === true || event.metaKey === true) && (event.key === '+' || event.key === '=' || event.key === '-' || event.key === '_'))
      event.preventDefault()
  }, false)
}

/**
 * 启用等比缩放
 * @element {HTMLElement} 元素
 * @containerSize {number} 容器宽度
 * @delay {number} 延迟
 * @byHeight {boolean} 是否根据高度缩放
 */
function enableScale(element, containerSize = 1920, delay = 0, byHeight = false) {
  if (byHeight) {
    setScaleByHeight(element, containerSize)
    window.addEventListener('resize', debounce(() => {
      setScaleByHeight(element, containerSize)
    }, delay), { passive: true })
  }
  else {
    setScaleByWidth(element, containerSize)
    window.addEventListener('resize', debounce(() => {
      setScaleByWidth(element, containerSize)
    }, delay), { passive: true })
  }
  // 禁止手动缩放
  disableManualScale()
}

export { enableScale }
